<template>
  <el-date-picker
    v-model="timePicker"
    type="daterange"
    :size="size"
    :clearable="clearable"
    unlink-panels
    range-separator="至"
    start-placeholder="开始日期"
    end-placeholder="结束日期"
    :picker-options="pickerOptions"
    value-format="timestamp">
  </el-date-picker>
</template>

<script>
export default {
  name: 'DatePicker', // 群组活跃的时间选择
  props: {
    size: { // 框大小
      type: String,
      default: 'normal',
    },
    clearable: {
      type: Boolean,
      default: true,
    },
    defaultRange: { // 不接收也不设置url的start end
      type: Array,
      default: () => ([]),
    },
  },
  data() {
    const dateRange = 1000 * 60 * 60 * 24 * 180; // 最多对180天的活跃进行统计
    let dateRangeMin = Date.now() - dateRange;
    let dateRangeMax = Date.now();
    const start = this.defaultRange[0] || this.$route.query.start_at;
    const end = this.defaultRange[1] || this.$route.query.end_at;
    return {
      // timePicker: [Date.now() - (1000 * 60 * 60 * 24 * 7), Date.now()], // 默认七天
      timePicker: [start, end],
      pickerOptions: { // 限制选择的天数
        onPick({ maxDate, minDate }) {
          if (!maxDate && minDate) {
            dateRangeMin = minDate.getTime() - dateRange;
            dateRangeMax = minDate.getTime() + dateRange;
            if (dateRangeMax > Date.now()) { dateRangeMax = Date.now(); }
          }
        },
        disabledDate(time) {
          return time.getTime() < dateRangeMin || time.getTime() > dateRangeMax;
        },
      },
    };
  },
  watch: {
    timePicker() {
      if (this.defaultRange.length) this.$emit('update:defaultRange', this.timePicker);
      else {
        const start = this.timePicker ? this.timePicker[0] : undefined;
        const end = this.timePicker ? this.timePicker[1] : undefined;
        this.$root.$emit('addQuery', { start_at: start, end_at: end });
      }
    },
  },
};
</script>

<style></style>
